﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using ChinaDynastyTours.Helpers;
using System.Threading;
using ChinaDynastyTours.Assets;

namespace ChinaDynastyTours.Views
{

    public partial class TeamGroupForm : DevExpress.XtraEditors.XtraForm
    {
        
        public TeamGroupForm()
        {
            InitializeComponent();
        }
        private void TeamGroupForm_Load(object sender, EventArgs e)
        {
            #region 初始化查询条件，并首次查询

            //默认为上月1日起，下下月1日止
            dateStart.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Month>1?DateTime.Now.Year:DateTime.Now.Year-1, DateTime.Now.Month>1?DateTime.Now.Month-1:12));
            dateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + DateTime.Now.Month / 11, (DateTime.Now.Month + 1) % 12 + 1));
            
            switch (ApplicationHelper.RankID)//根据当前登录用户级别,初始化部门列表和组团人列表
            {
                case 0://总经理 级别
                    departmentLookupEdit.DataSource = BaseInfoCtrl.GetDepartmentData(ApplicationHelper.RankID);
                    ownerALookUpEdit.DataSource = UserInfoCtrl.GetUserInfoData();
                    break;
                case 1://部门经理 级别
                    department.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    barStaticItem4.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    ownerALookUpEdit.DataSource = UserInfoCtrl.GetUserInfoData();
                    break;
                case 2://普通员工 级别
                    department.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    barStaticItem4.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnOnlyDisplayMyTourgroup.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    barStaticItem6.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    tbOwnerA.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;
                default: break;
            }

            btnRefresh.PerformClick();

            #endregion

        }

        private void btnSearch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string guestName = guestSearch.EditValue == null ? "" : guestSearch.EditValue.ToString();
            teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(guestName);
        }

        //查询团数据
        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            DevExpress.Utils.ToolTipController tip = ApplicationHelper.ShowLoadTip("正在加载数据...", teamGridControl);

            //记住当前选中行‘计划号’
            string focusedTourgroupID = "";
            if(teamGridView.FocusedRowHandle>=0)
                focusedTourgroupID = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle,"TourgroupID").ToString();//.FocusedRowHandle;

            TeamStateEnum teamState = comboStatus.EditValue == null ? TeamStateEnum.全部 : EnumHelper.Team_Str2Enum(comboStatus.EditValue.ToString(), true);
            DateTime dateStart = DateTime.Parse(this.dateStart.EditValue.ToString());
            DateTime dateEnd = DateTime.Parse(this.dateEnd.EditValue.ToString());
            
            //是否‘只显示我的团’（包括A、B角二者）
            string realname = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);
            //根据‘组团人’下拉列表过滤
            string ownerAB = tbOwnerA.EditValue == null ? "" : tbOwnerA.EditValue.ToString();
            if (btnOnlyDisplayMyTourgroup.Checked)
                teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(dateStart, dateEnd, teamState, realname, "", ownerAB);
            else 
            {
                string departmentId="";
                switch (ApplicationHelper.RankID)//否则根据当前登录用户级别进行显示
	            {
                    case 0://总经理 级别
                        departmentId = department.EditValue == null ? "" : department.EditValue.ToString();
                        teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(dateStart, dateEnd, teamState, "", departmentId, ownerAB);//根据选择的部门过滤
                        break;
                    case 1://部门经理 级别
                        departmentId = UserInfoCtrl.GetUserInfoForDepartmentID(Thread.CurrentPrincipal.Identity.Name);
                        teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(dateStart, dateEnd, teamState, "", departmentId, ownerAB);//根据登录用户所属部门过滤
                        break;
                    case 2://普通员工 级别
                        teamGridControl.DataSource = TeamGroupCtrl.GetTeamGroupData(dateStart, dateEnd, teamState, realname, "", ownerAB);//根据登录人过滤
                        break;
		            default:break;
	            }
            }
            //聚焦刷新前的行
            DataTable dt = teamGridControl.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["TourgroupID"].ToString().Trim() == focusedTourgroupID.Trim())
                {
                    teamGridView.FocusedRowHandle = teamGridView.GetRowHandle(i);
                    break;
                }
            }
            //teamGridView.FocusedRowHandle = focusedHandle;
            //处理窗口底层按钮可用状态
            btnImportPrice.Enabled = teamGridView.FocusedRowHandle >= 0;
            btnFillFeedback.Enabled = teamGridView.FocusedRowHandle >= 0;
            btnGuideFillFeedback.Enabled = teamGridView.FocusedRowHandle >= 0;
            btnPrintFeedback.Enabled = teamGridView.FocusedRowHandle >= 0;

            tip.HideHint();
        }


        #region 团的增、删、修改、复制、延期处理
		//添加团
        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewTourgroupForm form = new NewTourgroupForm();
            if (form.ShowDialog(this) == DialogResult.OK)
            {
                //if (form.tbStartDate.DateTime.ToString("yyyy-MM-dd") == "0001-01-01")
                //{
                //    MessageBox.Show("没有选择相应的日期，请重新选择", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    return;
                //}

                //生成新的计划号
                string newid = CreateNewTourGroupID(form.tbStartDate.DateTime);

                TourGroupEntity tourGroupTable = new TourGroupEntity();
                tourGroupTable.TourgroupID = newid;
                tourGroupTable.TourgroupName = "新建团";
                tourGroupTable.AdultNum = 0;
                tourGroupTable.ChildNum = 0;
                tourGroupTable.StartDate = form.tbStartDate.DateTime.ToString("yyyy-MM-dd");
                tourGroupTable.EndDate = form.tbStartDate.DateTime.ToString("yyyy-MM-dd");
                tourGroupTable.TourgroupState = EnumHelper.Team_Enum2Str(TeamStateEnum.计划);
                tourGroupTable.BuildGroupDate = DateTime.Now.ToString("yyyy-MM-dd");
                tourGroupTable.AdultNum = 0;
                tourGroupTable.ChildNum = 0;
                tourGroupTable.OwnerA = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);
                tourGroupTable.SaleTotalCost = 0;
                tourGroupTable.SaleTotalPrice = 0;
                tourGroupTable.BudgeTotalCost = 0;
                tourGroupTable.BudgeTotalPrice = 0;
                tourGroupTable.RealTotalCost = 0;
                tourGroupTable.RealTotalPrice = 0;
                tourGroupTable.StayOver = 0;
                tourGroupTable.AccompanyNum = 0;
                tourGroupTable.HasGuide = 0;
                tourGroupTable.DepartmentID = int.Parse(UserInfoCtrl.GetUserInfoForDepartmentID(Thread.CurrentPrincipal.Identity.Name));
                tourGroupTable.Currency = "人民币";
                tourGroupTable.CurrencyAmount = 0;
                tourGroupTable.ExchangeRate = 1;
                tourGroupTable.PriceMethod = "按人";

                TeamGroupCtrl.CreateTourGroup(tourGroupTable);

                //刷新
                dateEnd.EditValue = DateTime.Parse(this.dateEnd.EditValue.ToString()) >= form.tbStartDate.DateTime ? dateEnd.EditValue : form.tbStartDate.DateTime;
                dateStart.EditValue = DateTime.Parse(this.dateStart.EditValue.ToString()) <= form.tbStartDate.DateTime ? dateStart.EditValue : form.tbStartDate.DateTime;
                

                btnRefresh.PerformClick();
                DataTable dt = teamGridControl.DataSource as DataTable;
                dt.DefaultView.RowFilter = string.Format("TourgroupID='{0}'", newid);
                new TourGroupScheduleForm(dt.DefaultView).ShowDialog(this);
                
                //关闭窗口后，再次刷新
                btnRefresh.PerformClick();
            }
        }
        //删除
        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (teamGridView.FocusedRowHandle < 0) return;

            if (MessageBox.Show("确定删除选中的团信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string tourGroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                TeamGroupCtrl.UpdateTourGroupState(tourGroupId, TeamStateEnum.删除);

                //所有费用设置为取消
                ExpensesCtrl.UpdateExpenseStatusCanel(tourGroupId);
                
                //删除已安排导游
                GuideArrangeCtrl.DeleteGuideArrangebyTourgroupID(tourGroupId);

                //DataRowView drv = teamGridView.GetRow(teamGridView.FocusedRowHandle) as DataRowView;
                //TeamGroupCtrl.DeleteTourGroup(drv[0].ToString());
                //TeamGroupCtrl.DeleteTourGroupSchedule(drv[0].ToString());
            }
            //刷新
            btnRefresh.PerformClick();
        }

        //取消
        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (teamGridView.FocusedRowHandle < 0) return;

            if (MessageBox.Show("确定取消选中的团信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string tourGroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                TeamGroupCtrl.UpdateTourGroupState(tourGroupId, TeamStateEnum.取消);
                
                //所有费用设置为取消
                ExpensesCtrl.UpdateExpenseStatusCanel(tourGroupId);

                //删除已安排导游
                GuideArrangeCtrl.DeleteGuideArrangebyTourgroupID(tourGroupId);
            }
            //刷新
            btnRefresh.PerformClick();
        }
        //修改
        private void btnModify_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (teamGridView.FocusedRowHandle >= 0)
            {

                DataTable dt = teamGridControl.DataSource as DataTable;
                dt.DefaultView.RowFilter = string.Format("TourgroupID='{0}'", teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID"));
                new TourGroupScheduleForm(dt.DefaultView).ShowDialog(this);

            }

        }
        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string startDate = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "StartDate").ToString();
            string endDate = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "EndDate").ToString();
            string tourgroupName = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupName").ToString();

            CopyTourgroupForm form = new CopyTourgroupForm(startDate,endDate, tourgroupName);
            if (form.ShowDialog(this) == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;

                string oldTourGroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();

                string newTourGroupId = CreateNewTourGroupID(form._newStartDate);

                //Copy 指定团的一行数据
                TeamGroupCtrl.CopyTourGroup(oldTourGroupId, form._newStartDate, form._newEndtDate, newTourGroupId,form._newTourgroupName);

                //Copy 指定团的行程计划数据
                TeamGroupCtrl.CopyTourGroupSchedule(newTourGroupId,oldTourGroupId);

                //更新 拷贝指定团的行程计划日期
                TeamGroupCtrl.UpdateTourGroupScheduleDate(newTourGroupId, form._DateDifferNumber);

                HotelOrderCtrl.CopyHotelOrder(newTourGroupId, form._newTourgroupName, oldTourGroupId,form._DateDifferNumber);
                TravelOrderCtrl.CopyTravelOrder(newTourGroupId, form._newTourgroupName, oldTourGroupId);
 
                btnRefresh.PerformClick();//刷新
                Cursor.Current = Cursors.Default;
            }
        }

        private void btnDefer_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeferTourgroupForm form = new DeferTourgroupForm(teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "StartDate").ToString());
            if (form.ShowDialog(this) == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                
                string tourGroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                //更新团的起始截止日期
                TeamGroupCtrl.UpdateTourGroupStartAndEndDate(tourGroupId,form._StartDate,form._DateDifferNumber);
                //更新团行程计划的相关日期
                TeamGroupCtrl.UpdateTourGroupScheduleDate(tourGroupId, form._DateDifferNumber);
                btnRefresh.PerformClick();

                Cursor.Current = Cursors.Default;
            }
        }
        #endregion

        /// <summary>
        /// 生成新的团ID
        /// </summary>
        /// <returns></returns>
        private string CreateNewTourGroupID(DateTime startDate)
        {
            string Prefix="DT";
            string yy = startDate.ToString("yy");

            string id = TeamGroupCtrl.GetLastTourgroupID(Prefix + yy);
            string newID = "";
            if (!string.IsNullOrEmpty(id))
                newID = string.Format("{0}", int.Parse(id.Substring(4, 4)) + 1);//从第5位(0~4)开始取4位数字加1
            switch (newID.Length)
            {
                case 0:
                    newID = string.Format("{0}{1}", yy, "0001");
                    break;
                case 1:
                    newID = string.Format("{0}{1}{2}", yy, "000", newID);
                    break;
                case 2:
                    newID = string.Format("{0}{1}{2}", yy, "00", newID);
                    break;
                case 3:
                    newID = string.Format("{0}{1}{2}", yy, "0", newID);
                    break;
                case 4:
                    newID = string.Format("{0}{1}", yy, newID);
                    break;
                default:
                    newID = "Over";
                    break;
            }
            return Prefix+newID;
        }

        //团数据行单击事件
        private void teamGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)
            {
                Cursor.Current = Cursors.WaitCursor;

                DataTable dt = teamGridControl.DataSource as DataTable;
                //DataView dv = new DataView(dt);
                dt.DefaultView.RowFilter = string.Format("TourgroupID='{0}'",teamGridView.GetRowCellValue(e.RowHandle,"TourgroupID"));
                new TourGroupScheduleForm(dt.DefaultView).ShowDialog(this);
                btnRefresh.PerformClick();

                Cursor.Current = Cursors.Default;
            }
        }

        private void btnImportPrice_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string currentSelectedTourgroupId = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "TourgroupID").ToString();
                string currentSelectedCustomerName = teamGridView.GetRowCellValue(teamGridView.FocusedRowHandle, "CustomerName").ToString();
                int iValue = TeamGroupCtrl.LoadPriceExistChecked(openFileDialog1.FileName, currentSelectedTourgroupId);// LoadPriceDataFile(openFileDialog1.FileName);
                switch (iValue)
                {
                    case 0://系统中还不存在导入报价的团，请先建立团后再导入数据
                        MessageBox.Show("当前导入的销售报价数据与选择的团不符，请重新选择", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    case -1:
                        if (MessageBox.Show("此数据已经导入，确认重新导入吗？", "错误提示", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                            if (TeamGroupCtrl.LoadPriceDataFile(openFileDialog1.FileName, currentSelectedCustomerName) == true)
                                MessageBox.Show("导入成功！", "提示信息");
                            else
                                MessageBox.Show("导入失败，请查明原因！", "提示信息");
                        break;
                    case -2:
                        if (MessageBox.Show("确认导入报价数据吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            if (TeamGroupCtrl.LoadPriceDataFile(openFileDialog1.FileName, currentSelectedCustomerName) == true)
                                MessageBox.Show("导入成功！", "提示信息");
                            else
                                MessageBox.Show("导入失败，请查明原因！", "提示信息");
                        break;
                    case -3:
                        MessageBox.Show("导入数据不符合系统要求，请重新导入", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    case -4:
                        MessageBox.Show("所选文件为非报价数据文件，请重新选择", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    case -5:
                        MessageBox.Show("报价数据所属团状态不在‘计划’或‘成行’阶段，不允许导入！", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    default:
                        break;
                }
            }
        }

        private void teamGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;

            string tourgroupId = teamGridView.GetRowCellValue(e.FocusedRowHandle, "TourgroupID").ToString();
            
            #region 删除、取消、延期按钮状态控制


            switch (TeamGroupCtrl.GetTourGroupState(tourgroupId))
            {
                case TeamStateEnum.审核:
                case TeamStateEnum.终结:
                    btnDelete.Enabled = false;
                    btnCancel.Enabled = false;
                    btnDefer.Enabled = false;
                    btnImportPrice.Enabled = false; //‘导入销售报价’成行后不可用
                    break;
                case TeamStateEnum.成行:
                    btnDelete.Enabled = false;
                    btnCancel.Enabled = !(IncomeItemCtrl.GetIncomeItemReceivedPriceTotal(tourgroupId) > 0 || ExpensesCtrl.GetExpenseApplyPayTotal(tourgroupId) > 0);
                    btnDefer.Enabled = true;
                    btnImportPrice.Enabled = false;//‘导入销售报价’成行后不可用
                    break;
                case TeamStateEnum.计划:
                    btnDelete.Enabled = !(IncomeItemCtrl.GetIncomeItemReceivedPriceTotal(tourgroupId) > 0 || ExpensesCtrl.GetExpenseApplyPayTotal(tourgroupId) > 0);
                    btnCancel.Enabled = !(IncomeItemCtrl.GetIncomeItemReceivedPriceTotal(tourgroupId) > 0 || ExpensesCtrl.GetExpenseApplyPayTotal(tourgroupId) > 0);
                    btnDefer.Enabled = true;
                    btnImportPrice.Enabled = true;
                    break;
                case TeamStateEnum.取消:
                    btnDelete.Enabled = false;
                    btnCancel.Enabled = false;
                    btnDefer.Enabled = false;
                    btnImportPrice.Enabled = false;
                    break;

            }
            #endregion

        }


        private void teamGridView_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle < 0) return;
            object state = teamGridView.GetRowCellValue(e.RowHandle, "TourgroupRowState");

            if (state == null) return;

            switch (state.ToString())
            {
                case "0"://预留
                case "1"://预留
                    break;
                case "2"://此团为已经操作过（手工在计划中设置的）
                    e.Appearance.BackColor = Color.LightSteelBlue;
                    break;
                default:
                    break;
            }
            if (teamGridView.GetRowCellValue(e.RowHandle,"TourgroupState").ToString() == TeamStateEnum.取消.ToString())
                e.Appearance.BackColor = Color.Silver;

        }
    }
}
